#  Copyright 2012 Eric Lawrey, Australian Institute of Marine Science
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

# This function performs a "mail merge" type operation of the specified
# data frame with a given template. An output file is generated for
# each row in the data frame with a name based on the fileout pattern.
# Each of the other attributes in the data frame are attempted to be replaced
# in the template.
#
# EXAMPLE:
#   templateFile = "Template.txt"
#     Hello {person}, what a {day} day
#   templateTable = "Template.csv"
#     "person", "day"
#     "dave", "wonderful"
#     "fred", "sad"
#   fileout = "{day}-{person}.txt"
#  csv.merge("Template.txt","Template.csv", fileout)
#
# This would generate two files (wonderful-dave.txt and fred-dave.txt) with
# "Hello dave, what a wonderful day" and "Hello fred, what a sad day"
#
# This method does not perform substitutions within the templateTable. For
# this use columnSubstitute() first and pass templateTable as a data frame.
# templateTable <- read.csv(layerTableCsv, stringsAsFactors=FALSE)
# mergeTable <- columnSubstitute(templateTable)
# write.csv(mergeTable, file="merged-table.csv")
# template.merge("Template.txt", mergeTable, fileout="{day}-{person}.txt")
#
#
# templateFile - location or pattern of the template file to create for each row
#							in the templateTable. The pattern is applied after all the 
#							substitutions have been done in the templateTable. An example
#							pattern: styles/{SLD.STYLE.NAME}-template.sld
# templateString - If the template is already available and does not need to be read from
#							a files then specify the templateString. If it is not NA the
#							this will be used instead of templateFile (which will be ignored).
# templateTable - CSV file with all the data to substitute into the template. Generates
#							one file per row in this csv. Column names should be valid variable
#							names, and hence not use "-" or " " in the name. Dots are ok.
#							If templateTable is a dataframe rather than a string then it is
#							used directly rather than loading from a CSV file.
# fileout -			Name of the column to use as the generated filenames. Default is "fileout"
#							The fileout can be a pattern similar to a column in the spread sheet 
#							styles/{SLD.STYLE.NAME}.sld
#							If fileout is NA then the generated strings are returned in an array.
template.merge <- function (templateFile, templateString=NA, templateTable, fileout="fileout") {
	results <- c()
	for (i in 1:nrow(templateTable)) {
		if (!is.na(templateString)) {
			template <- templateString
		} else {
			# Apply subsitution to the template name 
			templateRow <- replaceText(
				templateFile,dataNames=names(templateTable), dataValues=templateTable[i,])
			template <- readText(templateRow)
		}
		genout <- replaceText(
			template, dataNames=names(templateTable), dataValues=templateTable[i,])
		
		if (!is.na(fileout)) {
			fileoutRow <- replaceText(
				fileout, dataNames=names(templateTable), dataValues=templateTable[i,])
			# Ensure the output path exists
			fileoutDir <- dirname(fileoutRow)
			if (!file.exists(fileoutDir)) {
				dir.create(fileoutDir, recursive=TRUE)
				print(paste("Creating directory: ",fileoutDir))
			}
			
			file.create(fileoutRow)
			cat(genout, file=fileoutRow)
			print(paste("Generated: ", fileoutRow, sep=""))
			flush.console()
		} else {
			results <- append(results,genout)
		}
	}
	return(results)
}